import re
import sys

def refactor_to_struct(file_path, function_name, prefix):
    try:
        # Step 1: Read the file content
        with open(file_path, "r") as file:
            c_code = file.read()
    except FileNotFoundError:
        print(f"Error: File not found: {file_path}")
        return None

    # Step 2: Extract local variable declarations with types
    local_var_pattern = r"(int|double|float|char|long|short|unsigned\s+int|signed|__int64|unsigned\s+__int64|float\s+\*|double\s+\*|__int64\s+\*|char\s+\[.*?\]|unsigned\s+__int64\s+\*|int\s+\*|double\s+\*|__int64\s+\[\d+\])\s+([\w]+)(?:\s*\[.*?\])?;"
    local_vars = re.findall(local_var_pattern, c_code)
    
    if not local_vars:
        print("No local variables found in the provided C function.")
        return c_code

    # Step 3: Define the struct name
    if function_name.startswith(prefix):
        struct_name = f"STRUCT_{function_name[len(prefix):].upper()}"
    else:
        struct_name = f"STRUCT_{function_name.upper()}"
    
    # Step 4: Create the struct definition
    struct_definition = [
        "#pragma pack(push, 1)\n",  # Add pragma to disable alignment
        f"typedef struct {{\n"
    ]
    for var_type, var_name in local_vars:
        struct_definition.append(f"    {var_type} {var_name};\n")
    struct_definition.append(f"}} {struct_name};\n")
    struct_definition.append("#pragma pack(pop)\n\n")  # Restore alignment
    
    # Step 5: Replace local variable declarations with struct instance
    refactored_code = re.sub(local_var_pattern, "", c_code)  # Remove local declarations
    refactored_code = re.sub(r"{", f"{{\n    {struct_name} vars = {{0}};\n", refactored_code, 1)  # Insert struct instance
    
    # Step 6: Replace variable references to use the struct
    for _, var_name in local_vars:
        refactored_code = re.sub(rf"\b{var_name}\b", f"vars.{var_name}", refactored_code)
    
    # Step 7: Add the struct definition at the beginning of the code
    refactored_code = "".join(struct_definition) + refactored_code
    
    return refactored_code

# Script entry point
if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Usage: python refactor_struct.py <file_path> <function_name> <prefix>")
        sys.exit(1)
    
    file_path = sys.argv[1]
    function_name = sys.argv[2]
    prefix = sys.argv[3]
    
    refactored_code = refactor_to_struct(file_path, function_name, prefix)
    if refactored_code:
        print("Refactored code:")
        print(refactored_code)

